package org.wltea.analyzer.help;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcSingleton {
    private static JdbcSingleton instance = null;

    private Connection connection;

    private JdbcSingleton() {
        // 私有构造函数，防止直接实例化对象
    }

    /**
     * getJdbcSingleton
     *
     * @return JdbcSingleton
     */
    public static JdbcSingleton getInstance() {
        if (instance == null) {
            synchronized (JdbcSingleton.class) {
                if (instance == null) {
                    instance = new JdbcSingleton();
                }
            }
        }
        return instance;
    }

    /**
     * getConnection
     *
     * @param url      url
     * @param username username
     * @param password password
     * @return Connection
     * @throws SQLException SQLException
     */
    public Connection getConnection(String url, String username, String password) throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(url, username, password);
        }
        return connection;
    }

    /**
     * closeConnection
     */
    public void closeConnection() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
